/**
 * 图片头数据加载就绪事件 - 更快获取图片尺寸
 * @version	2011.05.27
 * @author	TangBin
 * @see		http://www.planeart.cn/?p=1121
 * @param	{String}	图片路径
 * @param	{Function}	尺寸就绪
 * @param	{Function}	加载完毕 (可选)
 * @param	{Function}	加载错误 (可选)
 * @example imgReady('http://www.google.com.hk/intl/zh-CN/images/logo_cn.png', function () {
		//this.width,this.height
	});
 */
var imgReady = (function () {
	var list = [], intervalId = null,

	// 用来执行队列
	tick = function () {
		var i = 0;
		for (; i < list.length; i++) {
			list[i].end ? list.splice(i--, 1) : list[i]();
		};
		!list.length && stop();
	},

	// 停止所有定时器队列
	stop = function () {
		clearInterval(intervalId);
		intervalId = null;
	};

	return function (url, ready, load, error) {
		var onready, width, height, newWidth, newHeight,
			img = new Image();
		
		img.src = url;

		// 如果图片被缓存，则直接返回缓存数据
		if (img.complete) {
			ready.call(img);
			load && load.call(img);
			return;
		};
		
		width = img.width;
		height = img.height;
		
		// 加载错误后的事件
		img.onerror = function () {
			error && error.call(img);
			onready.end = true;
			img = img.onload = img.onerror = null;
		};
		
		// 图片尺寸就绪
		onready = function () {
			newWidth = img.width;
			newHeight = img.height;
			if (newWidth !== width || newHeight !== height ||
				// 如果图片已经在其他地方加载可使用面积检测
				newWidth * newHeight > 1024
			) {
				ready.call(img);
				onready.end = true;
			};
		};
		onready();
		
		// 完全加载完毕的事件
		img.onload = function () {
			// onload在定时器时间差范围内可能比onready快
			// 这里进行检查并保证onready优先执行
			!onready.end && onready();
		
			load && load.call(img);
			
			// IE gif动画会循环执行onload，置空onload即可
			img = img.onload = img.onerror = null;
		};

		// 加入队列中定期执行
		if (!onready.end) {
			list.push(onready);
			// 无论何时只允许出现一个定时器，减少浏览器性能损耗
			if (intervalId === null) intervalId = setInterval(tick, 40);
		};
	};
})();
//扩展
(function($){
	//私有方法
	var dopic = function(options,pic) {
		var settings = {
			next: '.next',  //图片元素列表翻页控制
			prev: '.prev',
			pic_prev:'.pic_prev',  //图片翻页控制
			pic_next:'.pic_next',
			picbox:'#picbox',//图片元素列表
			go:false,//pic 上一图 下一图控制开启
			hasdes:false,//.for_pic_desc
			des_o:'',//指定描述显示框 为空且开启描述就直接显示到 img后面 pic_desc_box
			des_s:'.for_pic_desc',
			curr:'curr',
			maxwidth:800,//图片最大宽度
			maxheight:0,
			width:0,//固定图片宽度
			height:0,
			base:'w',//图片大小以宽为准
			autoplay:false,
			direction:'y',//x 横向  y 纵向
			speed:800,
			opacity:0.5,
			disnum:0//不兼容设置可见列表数
			};
		settings = $.extend(settings,options);

		var picbox = $(settings.picbox);
		var piclist = picbox.children().first();//获取图片元素包含框
		$('body').prepend('<style type="text/css">.for_pic_desc{display:none;}</style>');
		//图片载入处理
		var loadimg = function(img,index){//图片元素 图片索引
			var litpic = img.attr('src');
			var src = img.attr('datasrc') ? img.attr('datasrc') : litpic;
		
			piclist.find('img.'+settings.curr).removeClass(settings.curr);//移动旧的选中
			img.addClass(settings.curr);//设置新的选中
					
			imgReady(src, function () {//仅以宽度做为缩放比例变量
				var height=this.height,width=this.width;
				
				if(settings.base=='w'){
					if(settings.width!=0){
						height = settings.height!=0 ? settings.height : parseInt(settings.width*height/width);
						width = settings.width;
					}else if(width>settings.maxwidth){
						height = parseInt(settings.maxwidth*height/width);
						width = settings.maxwidth;
					}
					if(height>settings.maxheight && settings.maxheight!=0) height = settings.maxheight;//重置图片框高度
				}else{
					if(settings.height!=0){
						width = settings.width!=0 ? settings.width : parseInt(settings.height*width/height);
						height = settings.height;
					}else if(height>settings.maxheight){
						width = parseInt(settings.maxheight*width/height);
						height = settings.maxheight;
					}
					if(width>settings.maxwidth && settings.maxwidth!=0) width = settings.maxwidth;//重置图片框宽度
				}
				$(pic).html('<img id="gallery_x_litimg" src="'+ litpic +'" width="'+ width +'" height="'+ height +'" style="width:'+width+'px;height:'+height+'px;position:absolute;left:50%;top:50%;margin-left:-'+ parseInt(width/2) +'px;margin-top:-'+ parseInt(height/2) +'px;background:transparent;" />');
				$(pic).css({'position':'relative'});
				
				//alert(index);
				if(settings.hasdes) {//加载描述
					var desc = piclist.find(settings.des_s).eq(index).html();//描述
					if(desc==undefined) desc='';
					if(settings.des_o!=''){//指定描述存放元素
						$(settings.des_o).html(desc);
					}else{
						if($('#pic_desc_box').html()!=undefined) $('#pic_desc_box').html(desc);
						else $(pic).after('<div id="pic_desc_box" class="pic_desc_box">'+ desc +'</div>');
					}
				}

				$('#gallery_y_big').remove();
				// 插入大图并使用逐渐清晰加载的效果
				$('#gallery_x_litimg').after('<img id="gallery_y_big" src="'+ src +'" style="width:'+width+'px;height:'+height+'px;position:absolute;left:50%;top:50%;margin-left:-'+ parseInt(width/2) +'px;margin-top:-'+ parseInt(height/2) +'px;background:transparent;" />');
			}, function(){//大图加载完毕
				$('#gallery_x_litimg').hide();
			});
		}
		
		var first = piclist.find('img').first();
		loadimg(first,0);
		var li_height = piclist.children().first().outerHeight(true);//单项高度
		var li_width = piclist.children().first().outerWidth(true);//单项宽度
		var li_num = 0;//列表数
		var curr_page=0;
		var pic_curr_index = 0;//当前图片索引
		var _btnPrev = $(settings.prev);//Shawphy:向上按钮
		var _btnNext = $(settings.next);//Shawphy:向下按钮
		var _picPrev = $(settings.pic_prev);//Shawphy:图片向上按钮
		var _picNext = $(settings.pic_next);//Shawphy:图片向下按钮
		var speed=settings.speed; //卷动速度，数值越大，速度越慢（毫秒）
		
		//透明
		var opacity=function(o,op){
			if(op) o.css({'cursor': 'default','opacity': settings.opacity,'filter': 'Alpha(opacity='+ settings.opacity*100 +')'});
			else o.css({'cursor': 'pointer','opacity': '1','filter': 'Alpha(opacity=100)'});
		}
		var chang_opacity=function(){
			if(curr_page==0) opacity(_btnPrev,true);else opacity(_btnPrev);
			if(curr_page==page-1) opacity(_btnNext,true);else opacity(_btnNext);
			if(settings.go){//图片上下控制
				if(pic_curr_index==0) opacity(_picPrev,true);else opacity(_picPrev);
				if(pic_curr_index==li_num-1) opacity(_picNext,true);else opacity(_picNext);
			}
			//alert(curr_page+'=='+page);
		}
		//遍历图片
		piclist.find('img').each(function(index){//给图片元素加载事件
			$(this).css("cursor","pointer");
			$(this).click(function(){
				pic_curr_index = index;
				loadimg($(this), pic_curr_index);
				chang_opacity();
			});
			li_num++;
		});
		settings.direction=='y' ? piclist.height(li_num*li_height) : piclist.width(li_num*li_width);
		var dis_li_num = settings.disnum;//可见列表数
		if(dis_li_num==0){
			dis_li_num = settings.direction=='y' ? picbox.height()/li_height : picbox.width()/li_width;//纵向 横向 可见数
			dis_li_num = Math.round(dis_li_num)>= dis_li_num ? Math.round(dis_li_num) : Math.round(dis_li_num)+1;
		}
		var page = li_num/dis_li_num;//页数
		if(dis_li_num>=li_num) page=1;
		else page = Math.round(page)>= page ? Math.round(page) : Math.round(page)+1;
		
		var upHeight=dis_li_num*li_height;//翻动高度picbox.height();//
		var upWidth=dis_li_num*li_width;//翻动宽度picbox.width();//
		
		//alert("picbox.height("+ picbox.height() +")\npicbox.width("+ picbox.width() +")\npiclist.height("+ piclist.height() +")\npiclist.width("+ piclist.width() +")\n li_width("+ li_width +")\n li_height("+ li_height +")\n dis_li_num("+ dis_li_num +")\n li_num("+ li_num +")\n page("+ page +")\nupWidth("+ upWidth +")\nupHeight("+ upHeight +")");
		var goPage=function(){//页面跳转
			//alert(curr_page);
			chang_opacity();
			_btnNext.unbind("click");
			_btnPrev.unbind("click");
			if(settings.direction=='y'){//上翻下翻定位页
				//alert('a');
				piclist.stop().animate({'margin-top': '-'+ curr_page*upHeight +'px'},speed,function(){
					_btnNext.bind("click",scrollDown);
					_btnPrev.bind("click",scrollUp); 
				});
			}else{//左翻右翻定位页
				piclist.stop().animate({'margin-left': '-'+ curr_page*upWidth +'px'},speed,function(){
					_btnNext.bind("click",scrollRight);
					_btnPrev.bind("click",scrollLeft); 
				});
			}
		}
		
		var go=function(a){//图片定位
			a==1 ? ++pic_curr_index : --pic_curr_index;
			//alert(pic_curr_index);
			if(pic_curr_index<0) {pic_curr_index=0;chang_opacity();return;}//
			if(pic_curr_index>=li_num) {pic_curr_index=li_num-1;chang_opacity();return;}// 
			
			curr_page = Math.floor(pic_curr_index/dis_li_num);//当前图片所在页数
			goPage();
			loadimg(piclist.find('img').eq(pic_curr_index), pic_curr_index);
			//return false;
		}

		var scrollUp=function(){//上翻
			curr_page--;
			if(curr_page<0) {curr_page=0;chang_opacity();return;}//
			goPage();
		}
		var scrollDown=function(){//下翻
			curr_page++;
			if(curr_page>=page) {curr_page=page-1;chang_opacity();return;}// 
			goPage();
		}
		var scrollLeft=function(){//左翻
			curr_page--;
			if(curr_page<0) {curr_page=0;chang_opacity();return;}//
			goPage();
		}
		var scrollRight=function(){//右翻
			curr_page++;
			if(curr_page>=page) {curr_page=page-1;chang_opacity();return;}// 
			goPage();
		}
		//鼠标事件绑定
		if(settings.direction=='y'){//纵向 横向 事件绑定
			_btnPrev.click( scrollUp );
			_btnNext.click( scrollDown );
		}else{
			_btnPrev.click( scrollLeft );
			_btnNext.click( scrollRight );
		}
		if(settings.go){//图片上下控制
			_picPrev.click( function(){go(-1);return false;} );
			_picNext.click( function(){go(1);return false;} );
		}
		chang_opacity();
	};
	//公开的
	$.fn.gallery_y = function(options) { 
		var pic = $(this);
		dopic(options,pic);
	}
})(jQuery);